package fr.mma.livraison;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.gson.Gson;

import fr.mma.livraison.dao.AdminDao;
import fr.mma.livraison.model.dto.reponse.ReponseDTO;

public abstract class AbstractServlet<T> extends HttpServlet {

	/** */
	private static final long serialVersionUID = 4973822371175513212L;
	

	final transient protected AdminDao dao = new AdminDao();

	/**
	 * Methode appelee lorsqu'on a recu un parametre en json.
	 * 
	 * @param dto
	 */
	abstract protected ReponseDTO postDTO(final T dto, String utilisateur);

	/**
	 * Methode appelee lorsqu'on n'a pas recu un parametre en json.
	 * 
	 * @param req la requete
	 * @param resp la reponse
	 */
	abstract protected void postEmpty(final HttpServletRequest req, final HttpServletResponse resp) throws IOException;

	abstract protected Class<T> getDTOClass();

	@Override
	protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		final String json = req.getParameter("json");
		if (StringUtils.isNotBlank(json)) {
			final Gson gson = new Gson();
			final T dto = gson.fromJson(json, getDTOClass());
			final String userName = req.getUserPrincipal() == null ? null : req.getUserPrincipal().getName();
			resp.setContentType("application/json");
			resp.getWriter().println(gson.toJson(postDTO(dto, userName)));
		} else {
			postEmpty(req, resp);
		}
	}
	
	protected boolean isAdmin(final HttpServletRequest req){
		return req.getUserPrincipal() != null && dao.isAdmin(req.getUserPrincipal().getName());
	}
}
